<template>
	<view class="box">
		<!-- <view class="" :style="{height:statusBarHeight + 'px',background:'linear-gradient(to right , #57c6cd, #79e3ea)'}"></view> -->
		<view class="" :style="{height:statusBarHeight + 'px',background:'#000'}"></view>
		<scroll-view :style="'height:calc(100% - '+(statusBarHeight+KeyboardHeight)+'px )'" scroll-y="true"
			:scroll-top="scrollTop">
			<view class="box_top">
				<text class="top_text">浙江大学附属邵逸夫医院</text>
			</view>
			<view class="box_center listBtcss" ref="listBtcss">
				<view class="center_top">
					<!-- 扫码出的结果 ：{{content}} -->
					<view class="center_top-title">{{ !showOrcode?'账号登录':'扫码登录'}}
					
					<!-- <img :src=" !showOrcode? ' ../../static/img/orcode_down.png':  '../../static/img/phone_down.png' " alt="" @tap="showOrcode = !showOrcode"> -->
					</view>
					<view v-if="!showOrcode">
						<Select class="SelectList" :disabled="false" :IndexIamge="true" v-model="hoseIndex" :options="options"
							@change="Swlshange"></Select>
						<u-form :model="form" ref='myForm'>
							<u-form-item prop="HosKind" leftIcon="../../static/img/hoser.svg">
								<u-input v-model="form.HosKind" class="form-item" placeholder="请输入科室代码" @confirm="doSearch(0)"
									@focus="focusValue(1)" />
							</u-form-item>
							<u-form-item prop="sUserid" leftIcon="../../static/img/user.svg">
								<u-input v-model="form.sUserid" type="string" placeholder="请输入用户名" @confirm="doSearch(1)"
									@focus="focusValue(2)"></u-input>
							</u-form-item>
							<u-form-item prop="sPassword" leftIcon="../../static/img/mima.svg">
								<u-input v-model="form.sPassword" :adjust-position="false" type="password"
									placeholder="请输入密码" @confirm="doSearch(2)" @focus="focusValue(3)"></u-input>
							</u-form-item>
						</u-form>
					</view>
				   <view class="orcode_block" v-else>
					   <img src="@/static/img/orcode.png" alt="" srcset="">
					   功能暂未开发完成
				   	   <text>扫一扫登录</text>
				   </view>
				</view>
				<view class="top_btn">
					<u-button type="primary" text="登录" color="#7ADFCA" @tap="SignIn"></u-button>
				</view>
			</view>
			<view class="box-bottom" v-if="show">
				<view class="bottom-top">
					<u-divider text="其他设置操作"></u-divider>
				</view>
				<view class="bottom-bottom">
					<u-button type="primary" :plain="true" text="设置" color="#7ADFCA" @tap="nav"></u-button>
					<u-button type="primary" :plain="true" text="同步" color="#7ADFCA" @tap="checkVersion"></u-button>
				</view>
			</view>
		</scroll-view>
		<scan-code></scan-code>
	</view>
</template>

<script>
	import scanCode from "../../components/html/scan-code.vue"
	import Select from '../ListOfPatients/selevt.vue'
	import {
		mapMutations,
		mapState
	} from "vuex";
	export default {
		data() {
			return {
				show: true,
				appVersion: '',
				appVersionCode: '',
				focus_index: -1,
				form: {
					HosKind: "",
					sUserid: "",
					sPassword: "",
					info: "",
					hoscode: ""
				},
				rules: {
					HosKind: [{
						required: true,
						message: "请输入用户名",
						trigger: "change"
					}],
					sUserid: [{
						required: true,
						message: "密码不小于1位",
						trigger: 'change',
						min: 1
					}],
					sPassword: [{
						required: true,
						message: "请输入科室",
						trigger: "change"
					}]
				},
				account: {},
				content: [],
				systemInfo: {},
				KeyboardHeight: 0,
				scrollTop: 0,
				statusBarHeight: 0,
				VauleIdx: 0,
				options: [{
					value: "A001",
					label: "A001庆春院区",
					hosecode: 'A001'
				}, {
					value: "A002",
					label: "A002钱塘院区",
					hosecode: 'A002'
				}],
				showOrcode:false
			}
		},
		computed: {
			...mapState('user', ['userInfo', 'gifArray', 'hoseIndex'])
		},
		components: {
			scanCode,
			Select
		},
		watch: {
			VauleIdx: {
				handler(newval) {
					console.log(newval);
					// this.$nextTick(() => {
					this.scrollTop = (60 * this.VauleIdx) - (this.VauleIdx * 2)
					// })
				},
				// deep: true,
			},
		},
		onLoad() {
			
			// let i  = 0
			// setInterval(()=>{
			// 	console.log(i++);
			// },3000)
			var _this = this
			_this.KeyboardHeightFun()
			
			uni.$on('scancodedate', function(content) {
				_this.form.sUserid = content
				_this.ScanLoginFun(content)
			})
			uni.getSystemInfo({
				success: (res) => {
					// console.log(res.appVersion)
					// console.log(res.appVersionCode)
					this.appVersion = res.appVersion
					this.appVersionCode = res.appVersionCode
					this.statusBarHeight = res.statusBarHeight
					uni.showToast({
						title: '版本号：' + res.appVersion,
						duration: 2000
					});
				}
			});
			const user = uni.getStorageSync('userInfo')
			if (user?.HosKind) {
				this.form = user
				this.form.sPassword = ''
				this.set_hoseIndex(user.hoscode)
			}
			_this.checkVersion()
			uni.getSystemInfo({
				success: (res) => {
					this.systemInfo = res
				}
			})
			console.log(_this.form, 'content');
		},

		methods: {
			...mapMutations("user", ["set_userInfo", "set_hoseIndex"]),
			Swlshange(e) {
				this.set_hoseIndex(e)
			},
			nav() {
				console.log('close')
				uni.navigateTo({
					url: '../network/index'
				});
			},
			doSearch(e) {
				this.focus_index = Number(e) + 1
			},
			focusValue(value) {
				this.VauleIdx = value
				console.log(value);
			},
			KeyboardHeightFun(value) {
				console.log(this.VauleIdx);
				if (this.VauleIdx == undefined) {
					return
				}
				uni.onKeyboardHeightChange(res => {
					this.KeyboardHeight = res.height
					if (res.height == 0) {
						this.scrollTop = 0
						this.show = true
						// this.statusBarHeight = 0
					} else {
						this.show = false
					}
				})
			},
			async ScanLoginFun(content) {
				try {
					if(!this.form.HosKind){
						uni.showToast({
							title: '请先输入科室代码,再扫描工牌!',
							duration: 1000,
							icon: "none", //自定义显示的图标，默认成功success，错误error,加载loading，不显示图标是none
						});
						return
					}
					const data = {
						HosKind: this.form.HosKind,
						barcode: content
					}
					let res = await this.$http.ScanLogin(data)
					if (res[0]?.password) {
						this.form.sPassword = res[0].password
						this.set_userInfo({...this.form,hoscode:this.hoseIndex})
						uni.removeStorageSync('gifArray')
						uni.redirectTo({
							url: '../hospitallist/index'
						});
					} else {
						console.log(555)
						uni.showToast({
							title: '用户名不存在或者密码错误',
							duration: 2000,
							icon: "none", //自定义显示的图标，默认成功success，错误error,加载loading，不显示图标是none
						});
					}
				} catch (e) {
					//TODO handle the exception
				}
			},
			async SignIn() {
				
				try {
					uni.showLoading({
						title: '登录中...', //显示的文字
						// duration: 5000, //显示多少时间，默认1500毫秒
						icon: "loading", //自定义显示的图标，默认成功success，错误error,加载loading，不显示图标是none
						mask: true
					})
					console.log(this.form);
					const res = await this.$http.Common_CheckUsePassword({
						HosKind: this.form.HosKind,
						sUserid: this.form.sUserid,
						sPassword: this.form.sPassword,
						info: '',
					})
					console.log(res);
					if (res.result == 1) {
						this.set_userInfo({...this.form,hoscode:this.hoseIndex})
						uni.removeStorageSync('gifArray')
						uni.hideLoading();
						uni.redirectTo({
							url: '../hospitallist/index'
						});
					} else if(res.statusCode===503){
						uni.showToast({
							title: '网络异常,登录失败!',
							duration: 2000,
							icon: "none", //自定义显示的图标，默认成功success，错误error,加载loading，不显示图标是none
						});
					}else{
						uni.showToast({
							title: '用户名或者密码错误!',
							duration: 1000,
							icon: "none", //自定义显示的图标，默认成功success，错误error,加载loading，不显示图标是none
						});
					}
				} catch (e) {
					//TODO handle the exception
				}
			},

			dddd(e) {
				this.doSearch(e)
			},
			change(e) {
				// console.log('change', e)
			},
			checkVersion() {
				//#ifdef APP-PLUS
				plus.runtime.getProperty(plus.runtime.appid, (widgetInfo) => {
					let currVersion = widgetInfo.versionCode;
					this.updateShowModel(widgetInfo, currVersion)
				});
				// #endif
			},

			/**
			 * 更新提示
			 * @param {string} url 
			 * @param {string} currVersion
			 */
			updateShowModel(widgetInfo, currVersion) {
				uni.request({
					url: 'http://192.1.3.243:8030/uploading/appVersions/queryAppVersions',
					method: "post", //传输类型
					data: {
						name: widgetInfo.name + 'APP',
					}, //必要参数
					success: (json) => {
						// console.log("----当前从服务端拉取的版本信息----:", json);
						if (!json || !json.data || !json.data.data.versions || !json.data.data.versions[0]) {
							return;
						}
						const versionData = json.data.data
						const versionInfo = versionData.versions;
						
						console.log(widgetInfo);
						console.log(versionInfo);
						console.log(this.userInfo.sPassword);
						// 判断版本是否需要更新
						if (currVersion != versionInfo) {
							let _this = this
							uni.showModal({
								title: `发现新版本`,
								content: '有新的版本发布，程序已启动自动更新。新版本下载完成后将自动弹出安装程序',
								// showCancel: !isForcedUpdate,
								success: function(res) {
									if (res.confirm) {
										_this.updateApp(versionData)
										// console.log('用户点击确定');
									} else if (res.cancel) {
										// console.log('用户点击取消');
									}
								}
							});
						}else if(this.form.sPassword){
							// uni.showModal({
							// 	title: '提示',
							// 	content: '检测到历史登录信息,是否直接登录?',
							// 	success:  (res)=> {
							// 		if (res.confirm) {
							// 		this.SignIn()	//自动登录
							// 		} else if (res.cancel) {
							// 			console.log('用户点击取消');
							// 		}
							// 	}
							// });
													
						}
					}
				})
			},

			/**
			 * 执行更新操作
			 * @param {Object} versionData
			 */
			updateApp(versionData) {
				console.log(versionData, 'versionDataversionData');
				// 如果有热更新配置文件，则热更
				if (versionData.path) {
					this.startAndroidUpdate(versionData);
					return;
				}
				switch (uni.getSystemInfoSync().platform) {
					case 'android':
						// 安卓安装包的apk地址
						plus.runtime.openURL(versionData.path);
						break
				}
			},

			/**
			 * 自动下载安装更新
			 * @param {Object} versionData 安装包地址相关信息
			 */


			startAndroidUpdate(versionData) {
				var showLoading;
				// 热更新的wgt文件
				let url = versionData.path;
				var dtask = plus.downloader.createDownload(
					url, {},
					function(d, status) {
						// 下载完成
						if (status == 200) {
							//console.log("----安装包文件地址----:",d, plus.io.convertLocalFileSystemURL(d.filename), d.filename);
							//plus.nativeUI.toast("软件开始安装重启");
							uni.request({
								url: 'http://192.1.3.243:8030/uploading/appVersions/editAppVersions', //接口地址。url
								method: "post", //传输类型
								data: {
									versions: versionData.versions,
									path: versionData.path,
									rdn: 2
								}, //必要参数
								// header: data.header,	//https 请求头参数
								success: (res) => {
									console.log("编辑成功！");
								}
							});
							showLoading.setTitle("  安装重启中...  ");
							plus.runtime.install(d.filename, {
								force: true
							}, e => {
								plus.nativeUI.closeWaiting();
								plus.runtime.restart();
							}, function(error) {
								console.log("----安装失败01----:", error);
								this.handleWgtInstallFail(versionData);
							})
						} else {
							console.log("----安装失败02----:", d, status);
							this.handleWgtInstallFail(versionData);
						}
					});
				try {
					var progress = 0;
					showLoading = plus.nativeUI.showWaiting("  开始下载  "); //创建一个showWaiting对象 
					dtask.start(); // 开启下载的任务
					dtask.addEventListener('statechanged', function(
						task,
						status
					) {
						// 给下载任务设置一个监听 并根据状态  做操作
						switch (task.state) {
							case 1:
								showLoading.setTitle("  正在下载 0%  ");
								break;
							case 2:
								showLoading.setTitle("已连接到服务器");
								break;
							case 3:
								progress = parseInt((parseFloat(task.downloadedSize) / parseFloat(task
										.totalSize)) *
									100);
								showLoading.setTitle("  正在下载" + String(progress).padStart(3, " ") + "%  ");
								break;
							case 4:
								//plus.nativeUI.closeWaiting();
								//下载完成
								break;
						}
					});
				} catch (err) {
					plus.nativeUI.closeWaiting();
					console.log("----安装失败03----:", err);
					this.handleWgtInstallFail(versionData);
				}
			},

			/**
			 * 热更新失败处理
			 * 
			 */
			handleWgtInstallFail(versionInfo) {
				plus.nativeUI.closeWaiting();
				uni.showModal({
					title: "温馨提示",
					content: "自动更新失败，是否手动更新",
					success: function(res) {
						if (res.confirm) {
							plus.runtime.openURL(versionInfo.path);
						}
					}
				});
			},

		}
	}
</script>
<style scoped lang="scss">
	::v-deep .SelectList {
		min-width: 84%;
		margin: 10rpx auto 0;
		height: 110rpx;
		border: none;
		border-top: 4rpx solid #f4f4f4;

		.ep-input-title {
			font-size: 36rpx;
			color: rgb(48, 49, 51);
			margin-left: 15px;
		}

		.ep-input-box {
			display: flex;
			align-items: center;
			padding-left: 0 !important;
			height: 100%;
		}

		.ep-picker-content-wrap .ep-picker-content .option-item {
			font-size: 32rpx;
			height: 60rpx !important;
			line-height: 60rpx;
		}
	}

	.box {
		width: 100%;
		height: 100vh;
		position: relative;
	}

	.box_top {
		width: 750rpx;
		height: 804rpx;
		// background: linear-gradient(225deg, #70E5EC 0%, #1B9EA6 100%);
		// border-bottom-right-radius: 404rpx;
		display: flex;
	
		background: url('../../static/img/heder.png') 0 -30rpx no-repeat;
		background-size: 100% 100%;

		.top_text {
			margin-top: 260rpx;
			font-size: 48rpx;
			font-family: SourceHanSansCN-Medium, SourceHanSansCN;
			font-weight: 500;
			color: #FFFFFF;
			line-height: 72rpx;
			padding-left: 40rpx;
		}
	}

	.box_center {
		// width: 100%;
		// height: 100%;
		position: absolute;
		top: 380rpx;
		left: 40rpx;
		
		.orcode_block{
			margin-top: 20rpx;
			display: flex;
			flex-direction: column;
			align-items: center;
			text{
				margin-top: 50rpx;
				font-size: 40rpx;
				font-weight: 400;
				color: #61CBD1;
			}
		}
	}

	.center_top {
		width: 670rpx;
		height: 562rpx;
		background: #FFFFFF;
		box-shadow: 4rpx 8rpx 20rpx 0 rgba(25, 58, 121, 0.15);
		border-radius: 6px;
		// transform: translateY(-160px);
		// margin: 0 auto;

		.top_input1 {
			padding: 70rpx 40rpx 0 60rpx;
			display: flex;
			align-items: center;

		}

		.center_top-title {
			font-size: 22px !important;
			font-family: SourceHanSansCN-Medium, SourceHanSansCN !important;
			font-weight: 500 !important;
			width: 85%;
			margin: 0 auto;
			color: #f9ae3d;
			line-height: 110rpx;
			
			img{
				float: right;
				margin-top: 16rpx;
				cursor: pointer;
			}
		}

	}

	.top_btn::v-deep {
		// height: 112rpx;
		box-shadow: 0 4rpx 12rpx 0 #6AC8B5;
		border-radius: 12rpx;
		width: 670rpx;
		margin: 44rpx auto 0;

		.u-button {
			height: 112rpx;
			background: #FFFFFF;
			border-radius: 12rpx;
			border: 2rpx solid #7ADFCA;

			text {
				font-size: 32rpx !important;
				font-family: SourceHanSansCN-Normal, SourceHanSansCN;
				font-weight: 400;
				line-height: 48rpx;
				letter-spacing: 24rpx;
			}
		}
	}

	.box-bottom {
		width: 100%;
		position: absolute;
		bottom: 0;
		left: 0;
	}

	::v-deep.bottom-top {
		width: 100%;
		margin: 22rpx 0;
		display: flex;
		align-items: center;
		justify-content: center;

		.u-line {
			width: 104rpx !important;
		}

		.u-divider {
			margin: 0;
		}

		.u-divider__text {
			margin: 0 50rpx;
			font-size: 28rpx;
			font-family: SourceHanSansCN-Normal, SourceHanSansCN;
			font-weight: 400;
			color: #999999;
			// line-height: 42rpx;
		}
	}

	.bottom-bottom {
		display: flex;
	}

	::v-deep .u-text__value {
		font-size: 40rpx !important;
		font-family: SourceHanSansCN-Medium, SourceHanSansCN !important;
		font-weight: 500 !important;
		line-height: 60rpx !important;
		padding: 20rpx 0 0 40rpx;
	}

	::v-deep .u-input {
		border: 0 !important;
		padding: 0 !important;

		.u-input__content__prefix-icon {
			margin-right: 44rpx !important;
		}
	}

	::v-deep .bottom-bottom {
		margin-bottom: 36rpx;

		.u-button {
			width: 316rpx;
			height: 100rpx;
			background: #FFFFFF;
			border-radius: 12rpx;
			border: 2rpx solid #7ADFCA;

			text {
				font-size: 32rpx;
				font-family: SourceHanSansCN-Normal, SourceHanSansCN;
				font-weight: 400;
				color: #7ADFCA;
				line-height: 48rpx;
				letter-spacing: 24rpx;
			}
		}
	}

	::v-deep {
		// .u-form-item {
		// 	padding: 50rpx 0 0 0;
		// }

		.u-form-item__body {
			padding: 0 !important;
			height: 108rpx;
			border-top: 4rpx solid #f4f4f4;
			width: 85%;
			margin: 0 auto;
		}

		.u-input__content__field-wrapper__field {
			font-size: 36rpx !important;
		}

		.u-form-item__body__left__content {
			padding-right: 0 !important;
			// padding-left: 58rpx;
		}

		.u-icon__img {
			width: 60rpx !important;
			height: 60rpx !important;
		}
	}
</style>
